import request from './request.js'
import storage from '../storage/storage.js'
// get请求
export function login(params) {
	return new Promise((resolve, reject) => {
		request.post("login/submit", params).then((result) => {
			uni.hideLoading();
			// 写入sessionID
			storage.set("sessionId", result.data.msg)
			resolve(result)
		}).catch(err => {
			uni.hideLoading();
			reject(err)
		});
	});
}
export function loginCode(params) {
	return new Promise((resolve, reject) => {
		request.get("login/code/"+params,'').then((result) => {
			uni.hideLoading();
			// 写入sessionID
			resolve(result.data)
		}).catch(err => {
			uni.hideLoading();
			reject(err.data)
		});
	});
}

// post请求
export function register(params) {
	return new Promise((resolve, reject) => {
		request.post("login/register", params).then((result) => {
			uni.hideLoading();
			resolve(result);
		}).catch((error) => {
			uni.hideLoading();
			reject(error);
		});
	});
}
// 防止用户错误之后，请求次数过多
var httpRequestNum = 0
// 如果说比较懒，或者是不想这么麻烦，也可直接用这两个，调用的时候第一个参数换成接口地址即可
export function httpGet(url, params) {
	if (! request.errorMsg()) {
		return false
	} else {
		return new Promise((resolve, reject) => {
			request.get(url, params).then((result) => {
				httpRequestNum = 0
				uni.hideLoading();
				resolve(result)
			}).catch(err => {
				uni.hideLoading();
				if(err.data.msg==null){
					httpRequestNum++
					if(httpRequestNum < 3){
						autoLogin().then(sucess=>{
							httpGet(url,params)
						})
					}
				}
				reject(err)
			});
		});
	}
}

export function httpPost(url, params) {
	if (!request.errorMsg(url)) {
		return false
	} else {
		return new Promise((resolve, reject) => {
			request.post(url, params).then((result) => {
				httpRequestNum = 0
				resolve(result)
				uni.hideLoading();
			}).catch(err => {
				if(err.data.msg==null){
					httpRequestNum++
					if(httpRequestNum < 3){
						autoLogin().then(sucess=>{
							httpPost(url,params)
						})
					}
				}
				reject(err)
			});
		});
	}
}
// 自动登录
function autoLogin(){
	return new Promise((resolve,reject)=>{
		let user= storage.get("loginUser")
		login(user).then(sucess=>{
			resolve(sucess) 
		}).catch(error=>{
			reject(error)
		})
	})
	
}
